﻿using d1Common.WebController;
using d1Project.Modules.Common.do4A.Models;
using d1Project.Tools;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace d1Project.Modules.Common.do4A.Controllers.a2
{
    [Route("do4A/a2/MyPassword")]
    public class MyPassword2Controller : Authorize2Controller
    {
        protected override DbContext dbContext
        {
            get
            {
                return this.db;
            }
        }
        private do4ADbContext db = new do4ADbContext();
        public async Task<IHttpActionResult> Put(User2PwdsVm model)
        {
            if (string.IsNullOrEmpty(model.Password)) this.Error("新密码不能为空");

            var _user2 = await db.User2s.FindAsync(this.UserId);
            if (_user2 == null) this.Error("用户不存在");

            var entity = await db.User2Pwds.FindAsync(this.UserId);
            if (entity == null)
            {
                User2Pwd user2Pwd = new User2Pwd();
                user2Pwd.Id = this.UserId;
                user2Pwd.Password = model.Password;
                db.User2Pwds.Add(user2Pwd);
            }
            else
            {
                entity.Password = model.Password;
            }
            await db.SaveChangesAsync();
            return Ok();
        }
    }

    public class User2PwdsVm
    {
        [Required]
        public string Password { get; set; }
    }
}
